package org.jtb.quickr;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.Logger;

class Post extends HttpVerb {
    static Logger logger = Logger.getLogger(Post.class.getName());
    
    private Map<String,Object> params;
    
    public Post(URL url, Map<String,Object> params) {
        super(url);
        this.params = params;
    }    

    protected Map<String,Object> getParameters() {
        return params;
    }
    
    public InputStream execute() throws QuickrException {
        PostMethod postMethod = new PostMethod(getUrl().toString());
        
        addPostParameters(postMethod);
        
        InputStream is = null;
        HttpClient httpClient = getHttpClient();

        try {
            int status = httpClient.executeMethod(postMethod);
            if (status != 200) {
                throw new QuickrException("post failed, status: " + status);
            }
            
            if (logger.isDebugEnabled()) {
                String response = postMethod.getResponseBodyAsString();
                logger.debug("post response:\n" + response);
            }
            
            is = postMethod.getResponseBodyAsStream();
        } catch (IOException ioe) {
            throw new QuickrException("could not post to URL: " + getUrl());
        }
        
        return is;    
    }
        
    protected void addPostParameters(PostMethod method) throws QuickrException {
        for (String key: params.keySet()) {
            String val = (String)params.get(key);
            method.addParameter(key, val);
        }
    }
}
